﻿using Itech_Run.HttpApi.Shared.Result;
using Itech_Run.HttpApi.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Itech_Run.Sys.HttpApi.Controllers
{
    public class FileUploadController : BaseApiController
    {
        [HttpPost]
        public async Task<CustomResult> Upload([FromForm] List<IFormFile> files)
        {
            string folder = "Upload";
            var lastFileUrl = "";
            foreach (var formFile in files)
            {
                var urlPrefix = Request.Scheme + "://" + Request.Host.Value;
                var guid = Guid.NewGuid().ToString();
                var fileName = formFile.FileName;
                string path = Directory.GetCurrentDirectory() + string.Format($"\\Files\\{folder}\\{guid}\\{fileName}");
                string url = urlPrefix + string.Format($"/Files/{folder}/{guid}/{fileName}");

                FileInfo fi = new FileInfo(path);
                var directory = fi.Directory;
                if (directory != null && !directory.Exists)
                    directory.Create();
                using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    await formFile.CopyToAsync(stream);
                    lastFileUrl = url;
                }
            }

            return new CustomResult(lastFileUrl);
        }
    }
}
